public class P4
{
	public static final int EMPTY = -1;
	public static final int PLAYER1 = 0;
	public static final int PLAYER2 = 1;

	public static final int HEIGHT = 6;
	public static final int WIDTH = 7;

	public static final int COLONNE_NON_VALIDE = -1;

	private IPlayer[] player = new IPlayer[2];
	private GridFrame gridframe;
	private Grid grid;

	public P4()
	{
		gridframe = new GridFrame();
		gridframe.setVisible(true);
	}

	public void newGame(Grid g, IPlayer p1, IPlayer p2)
	{
		player[PLAYER1] = p1;
		player[PLAYER2] = p2;
		gridframe.addMouseListener(player[PLAYER1]);
		gridframe.addMouseListener(player[PLAYER2]);
		grid=g;
	}

	public void play()
	{
		int p = PLAYER1;
		int colonne;
		int ligne;
		boolean end=false;

		while(!end)
		{
			do
			{
				colonne=player[p].play();
				ligne=grid.put(colonne);
				System.out.println(colonne);
			}while(ligne==COLONNE_NON_VALIDE);

			gridframe.setIcon(ligne, colonne, p);
			if(grid.win(p))
				end=true;
			if(grid.full())
				end=true;	

			if (p==PLAYER1)
				p=PLAYER2;
			else
				p=PLAYER1;

			grid.switchJoueur();
		}
		
		// save final state (and let the other player know the last input)
		Fichier.save("buffer.tmp", grid);
	}

	public void end()
	{
		if(grid.win(PLAYER1))
			System.out.println("Le joueur 1 est le gagnant !");
		else if(grid.win(PLAYER2))
			System.out.println("Le joueur 2 est le gagnant !");
		else
			System.out.println("Match nul !");	
	}
}